{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "c52ea2f9-03ff-4647-b782-46867ebed04e",
      "metadata": {
        "id": "c52ea2f9-03ff-4647-b782-46867ebed04e"
      },
      "source": [
        "# Filtering and trimming messages\n",
        "\n",
        "## Review\n",
        "\n",
        "Now, we have a deeper understanding of a few things:\n",
        "\n",
        "* How to customize the graph state schema\n",
        "* How to define custom state reducers\n",
        "* How to use multiple graph state schemas\n",
        "\n",
        "## Goals\n",
        "\n",
        "Now, we can start using these concepts with models in LangGraph!\n",
        "\n",
        "In the next few sessions, we'll build towards a chatbot that has long-term memory.\n",
        "\n",
        "Because our chatbot will use messages, let's first talk a bit more about advanced ways to work with messages in graph state."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "d5197aba-5d46-421b-ae3b-4e3034edcfda",
      "metadata": {
        "id": "d5197aba-5d46-421b-ae3b-4e3034edcfda"
      },
      "outputs": [],
      "source": [
        "%%capture --no-stderr\n",
        "%pip install --quiet -U langchain_core langgraph langchain_google_genai"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "768dc606-d5f2-468d-96ea-910b264e0f8a",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "768dc606-d5f2-468d-96ea-910b264e0f8a",
        "outputId": "2d063afc-8fd9-43b0-cbb1-25e1df82ad3e"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "env: GOOGLE_API_KEY=AIzaSyCD_du_wlnoyfrBSnS9k-fyqcs-C2VKqI4\n",
            "AIzaSyCD_du_wlnoyfrBSnS9k-fyqcs-C2VKqI4\n"
          ]
        }
      ],
      "source": [
        "from google.colab import userdata\n",
        "\n",
        "%env GOOGLE_API_KEY = {userdata.get('GEMINI_API_KEY')}\n",
        "\n",
        "import os\n",
        "print(os.environ[\"GOOGLE_API_KEY\"])"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8b64d8d3-e4ac-4961-bdc0-688825eb5864",
      "metadata": {
        "id": "8b64d8d3-e4ac-4961-bdc0-688825eb5864"
      },
      "source": [
        "We'll use [LangSmith](https://docs.smith.langchain.com/) for [tracing](https://docs.smith.langchain.com/concepts/tracing).\n",
        "\n",
        "We'll log to a project, `langchain-academy`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "dd020c79",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "dd020c79",
        "outputId": "ce100d1b-c3e8-4451-e3e0-7dbc3749131e"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "env: LANGCHAIN_API_KEY=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\n"
          ]
        }
      ],
      "source": [
        "%env LANGCHAIN_API_KEY = {userdata.get('LANGCHAIN_API_KEY')}\n",
        "os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
        "os.environ[\"LANGCHAIN_PROJECT\"] = \"langchain-academy\""
      ]
    },
    {
      "cell_type": "markdown",
      "id": "72f3fc90-58b6-4f7f-897e-dddf6ae532c7",
      "metadata": {
        "id": "72f3fc90-58b6-4f7f-897e-dddf6ae532c7"
      },
      "source": [
        "## Messages as state\n",
        "\n",
        "First, let's define some messages."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "cf11a463-e27a-4a05-b41d-64882e38edca",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "cf11a463-e27a-4a05-b41d-64882e38edca",
        "outputId": "b6655be9-9d89-4f1e-932a-f5197385a8a6"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
            "Name: Bot\n",
            "\n",
            "So you said you were researching ocean mammals?\n",
            "================================\u001b[1m Human Message \u001b[0m=================================\n",
            "Name: Lance\n",
            "\n",
            "Yes, I know about whales. But what others should I learn about?\n"
          ]
        }
      ],
      "source": [
        "from pprint import pprint\n",
        "from langchain_core.messages import AIMessage, HumanMessage\n",
        "messages = [AIMessage(f\"So you said you were researching ocean mammals?\", name=\"Bot\")]\n",
        "messages.append(HumanMessage(f\"Yes, I know about whales. But what others should I learn about?\", name=\"Lance\"))\n",
        "\n",
        "for m in messages:\n",
        "    m.pretty_print()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b814adcb-6bf9-4b75-be11-e59f933fbd0c",
      "metadata": {
        "id": "b814adcb-6bf9-4b75-be11-e59f933fbd0c"
      },
      "source": [
        "Recall we can pass them to a chat model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "4712e288-e622-48a2-ad3f-a52f65f3ab08",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "4712e288-e622-48a2-ad3f-a52f65f3ab08",
        "outputId": "dbe7284d-b215-4aca-8d20-01f2cd2de1e5"
      },
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "AIMessage(content='That\\'s great! Whales are fascinating, but there\\'s a whole world of amazing ocean mammals beyond them. Here are a few categories to get you started, with examples:\\n\\n**1. Marine Mammals with Flippers:**\\n\\n* **Dolphins:**  These intelligent and social creatures come in many species, each with unique characteristics and behaviors.\\n* **Porpoises:** Smaller and more stout than dolphins, porpoises have a distinctive triangular dorsal fin.\\n* **Sea Lions and Seals:** These pinnipeds (meaning \"fin-footed\") spend much of their time on land, but are skilled swimmers. \\n    * **Sea Lions:** Have external ear flaps and can rotate their hind flippers forward for walking.\\n    * **Seals:** Lack external ear flaps and use their bellies to \"waddle\" on land.\\n\\n**2. Mammals that Live in the Arctic and Antarctic:**\\n\\n* **Walruses:** Large, tusked animals that use their tusks for digging, fighting, and hauling themselves onto ice. \\n* **Polar Bears:** The world\\'s largest land predator, adapted for life in icy conditions.\\n* **Sea Otters:** The smallest marine mammal, known for their thick fur and use of tools.\\n\\n**3. Other Interesting Ocean Mammals:**\\n\\n* **Manatees and Dugongs:**  Herbivorous, gentle giants that live in warm, shallow waters.\\n* **Sea Cows:** These extinct relatives of manatees were once common, but are now only known from fossils.\\n* **River Dolphins:**  Several species of dolphins live in freshwater rivers around the world, often facing threats from habitat loss and pollution.\\n\\n**Tips for Research:**\\n\\n* **Focus on specific species:** There are many fascinating facts to learn about each species of ocean mammal.\\n* **Explore their biology:** Dive deep into their anatomy, physiology, and adaptation to their environment.\\n* **Learn about their behavior:** How do they communicate, mate, raise their young, and hunt for food?\\n* **Investigate their conservation status:** Many ocean mammals are facing threats from pollution, habitat loss, and climate change.\\n\\nI hope this gives you a good starting point for your research! Let me know if you have any other questions. \\n', additional_kwargs={}, response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'safety_ratings': [{'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', 'probability': 'NEGLIGIBLE', 'blocked': False}]}, id='run-27e46c60-e713-4163-bbad-7ccdfb3c723c-0', usage_metadata={'input_tokens': 26, 'output_tokens': 467, 'total_tokens': 493})"
            ]
          },
          "metadata": {},
          "execution_count": 8
        }
      ],
      "source": [
        "from langchain_google_genai import ChatGoogleGenerativeAI\n",
        "llm: ChatGoogleGenerativeAI = ChatGoogleGenerativeAI(model = \"gemini-1.5-flash\")\n",
        "llm.invoke(messages)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "fbd1dab8-0af8-4621-8264-ce65065f76ec",
      "metadata": {
        "id": "fbd1dab8-0af8-4621-8264-ce65065f76ec"
      },
      "source": [
        "We can run our chat model in a simple graph with `MessagesState`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "id": "bbd8c39c-633b-4176-9cc6-8318e42bb5dd",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 251
        },
        "id": "bbd8c39c-633b-4176-9cc6-8318e42bb5dd",
        "outputId": "4b556a13-665b-49f2-86b3-d2db04601fe6"
      },
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "image/jpeg": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAAAAAAAb6IAADj1AAADkFhZWiAAAAAAAABimQAAt4UAABjaWFlaIAAAAAAAACSgAAAPhAAAts9YWVogAAAAAAAA9tYAAQAAAADTLXBhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAAABtbHVjAAAAAAAAAAEAAAAMZW5VUwAAACAAAAAcAEcAbwBvAGcAbABlACAASQBuAGMALgAgADIAMAAxADb/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCADqAIIDASIAAhEBAxEB/8QAHQABAAMAAwEBAQAAAAAAAAAAAAUGBwMECAIBCf/EAEwQAAEDBA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JAV5UY0SO/wDT+sftqyIEWe2h5IZkIUPRcGlAj6jX74lH/wCg1/oFdc1Mroa3fsoZFxLtlr4sOWG642qx535vS1OS7KJjLrchp5soIJ2UpWNcyebQPKetcL/Dt+VjdvNowKFiMoZHbpb8OK7H51xmHkrLjikaTtILmkgqOu7qdVszbDbO+zbSjffygDdfda7yaGJuKK933bNbu1gxniJwvvuWX3N3oTTTSZtutZgPPuJ7N6RGkOPFtQB5gD6A2Rr0vXo12YUy+u8SYWX5RYm8OssCySIb8mdc460JdcfYUkFSVdEnlOif89dN67X4tCXElKkhST3gjYqXkyraTf8ANv5YKoOLmCqOhmmPH19Lqx/51zQ+KGG3GWzFiZbYpUp9YbaYZuTK1uLJ0EpSFbJJ6ACrB4jG+Ttf6BX6IjCCFBltJHUEIHSs1JmK3fsg5a1zgPCW3jFxnrHoTrg4tok96EJQ1+zmbWf86zjEcUl59LLMJS2bclXLJuaAOVv40Nk9FOd46bCe9XqSr0RbbdGtFvjQYbSWIkZtLTTSe5CUjQH7BXO9NZVAoM3hel36i60I7NKUrjgKUpQClKUApSlAVS98LMVyCUuTLs7SZLh5nH4i1xnHD8alNKSVH6zuo1XA/EVKJMWfs9el1lD/APSr7StuHLMpgVmGZEltZNWUH4DcR+Sz/wB7S/e0+A3Efks/97S/e1fqVfPsq+rFvYqyg/AbiPyWf+9pfvafAbiPyWf+9pfvav1KZ9lX1Yt7FWUH4DcR+Sz/AN7S/e1zxuC+HRng4q0GWR+hOlPSUH7UOLUk/sq70qHluVNUc2LexVnwww3GZQ0y2lppCQlCEJASkDuAA7hX3SlaRApSlAKUpQH/2Q==\n",
            "text/plain": [
              "<IPython.core.display.Image object>"
            ]
          },
          "metadata": {}
        }
      ],
      "source": [
        "from IPython.display import Image, display\n",
        "from langgraph.graph import MessagesState\n",
        "from langgraph.graph import StateGraph, START, END\n",
        "from langgraph.graph.state import CompiledStateGraph\n",
        "\n",
        "# Node\n",
        "def chat_model_node(state: MessagesState) -> MessagesState:\n",
        "    return {\"messages\": llm.invoke(state[\"messages\"])}\n",
        "\n",
        "# Build graph\n",
        "builder: StateGraph = StateGraph(MessagesState)\n",
        "builder.add_node(\"chat_model\", chat_model_node)\n",
        "builder.add_edge(START, \"chat_model\")\n",
        "builder.add_edge(\"chat_model\", END)\n",
        "graph: CompiledStateGraph = builder.compile()\n",
        "\n",
        "# View\n",
        "display(Image(graph.get_graph().draw_mermaid_png()))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "id": "3a5a3e4a-ccfd-4d14-81f1-f0de6e11a1e4",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "3a5a3e4a-ccfd-4d14-81f1-f0de6e11a1e4",
        "outputId": "94337b21-424e-481b-a115-3295b1b893ee"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
            "Name: Bot\n",
            "\n",
            "So you said you were researching ocean mammals?\n",
            "================================\u001b[1m Human Message \u001b[0m=================================\n",
            "Name: Lance\n",
            "\n",
            "Yes, I know about whales. But what others should I learn about?\n",
            "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
            "\n",
            "That's great! Whales are fascinating. There's a whole world of marine mammals beyond them, though.  Here are some categories to explore:\n",
            "\n",
            "**1.  The \"Big Three\"**:\n",
            "\n",
            "* **Dolphins:**  There are over 40 species, from the playful bottlenose to the sleek orcas. \n",
            "* **Porpoises:**  Smaller, more stout, and often confused with dolphins.  \n",
            "* **Whales:**  You know them, but there are many more than just the big ones!  \n",
            "\n",
            "**2.  The \"Seals and Sea Lions\"**:\n",
            "\n",
            "* **Seals:**  These are the ones you see sunning themselves on rocks.  They have flippers and can't walk on land well.\n",
            "* **Sea Lions:**  Larger, with external ear flaps and the ability to walk on land (they're more \"lion-like\"). \n",
            "\n",
            "**3.  The \"Others\"**:\n",
            "\n",
            "* **Manatees and Dugongs:**  These are the \"sea cows,\" herbivores that live in warm waters.\n",
            "* **Sea Otters:**  The smallest marine mammal, known for its thick fur and playful nature.\n",
            "* **Polar Bears:**  Though not technically \"ocean\" mammals, they spend much of their time on sea ice and rely heavily on the ocean for food.\n",
            "\n",
            "**To make your research even more focused, consider:**\n",
            "\n",
            "* **Geographical regions:**  Are you interested in Arctic mammals, tropical ones, or a specific ocean?\n",
            "* **Specific behaviors:**  Do you want to learn about communication, migration, or social structures?\n",
            "* **Conservation status:**  Are you curious about endangered species or those facing threats?\n",
            "\n",
            "Let me know what you'd like to focus on, and I can help you find more specific information!\n"
          ]
        }
      ],
      "source": [
        "output = graph.invoke({'messages': messages})\n",
        "for m in output['messages']:\n",
        "    m.pretty_print()"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "async for m in graph.astream_events({'messages': messages}, version=\"v2\"): # The version argument is now correctly passed as a keyword argument.\n",
        "      print(m)\n",
        "      print(\"\\n--------------\\n\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "4Kl4lGlZyxej",
        "outputId": "ba627553-5f61-411b-d70c-98494367cc30"
      },
      "id": "4Kl4lGlZyxej",
      "execution_count": 25,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{'event': 'on_chain_start', 'data': {'input': {'messages': [AIMessage(content='So you said you were researching ocean mammals?', additional_kwargs={}, response_metadata={}, name='Bot', id='dcdce2ba-dfef-454b-8815-2beefb201928'), HumanMessage(content='Yes, I know about whales. But what others should I learn about?', additional_kwargs={}, response_metadata={}, name='Lance', id='314874d6-df07-4183-bb67-2aeded96d302')]}}, 'name': 'LangGraph', 'tags': [], 'run_id': '8b70b221-ceba-40bc-abb5-44199db7154d', 'metadata': {}, 'parent_ids': []}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_start', 'data': {'input': {'messages': [AIMessage(content='So you said you were researching ocean mammals?', additional_kwargs={}, response_metadata={}, name='Bot', id='dcdce2ba-dfef-454b-8815-2beefb201928'), HumanMessage(content='Yes, I know about whales. But what others should I learn about?', additional_kwargs={}, response_metadata={}, name='Lance', id='314874d6-df07-4183-bb67-2aeded96d302')]}}, 'name': '__start__', 'tags': ['graph:step:0', 'langsmith:hidden', 'langsmith:hidden'], 'run_id': '2268d89a-03c5-4022-9be8-ffe20a2058f9', 'metadata': {'langgraph_step': 0, 'langgraph_node': '__start__', 'langgraph_triggers': ['__start__'], 'langgraph_path': ('__pregel_pull', '__start__'), 'langgraph_checkpoint_ns': '__start__:c814c808-4e66-2f9c-4a4b-67aea5ea7e46'}, 'parent_ids': ['8b70b221-ceba-40bc-abb5-44199db7154d']}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_end', 'data': {'output': {'messages': [AIMessage(content='So you said you were researching ocean mammals?', additional_kwargs={}, response_metadata={}, name='Bot', id='dcdce2ba-dfef-454b-8815-2beefb201928'), HumanMessage(content='Yes, I know about whales. But what others should I learn about?', additional_kwargs={}, response_metadata={}, name='Lance', id='314874d6-df07-4183-bb67-2aeded96d302')]}, 'input': {'messages': [AIMessage(content='So you said you were researching ocean mammals?', additional_kwargs={}, response_metadata={}, name='Bot', id='dcdce2ba-dfef-454b-8815-2beefb201928'), HumanMessage(content='Yes, I know about whales. But what others should I learn about?', additional_kwargs={}, response_metadata={}, name='Lance', id='314874d6-df07-4183-bb67-2aeded96d302')]}}, 'run_id': '2268d89a-03c5-4022-9be8-ffe20a2058f9', 'name': '__start__', 'tags': ['graph:step:0', 'langsmith:hidden', 'langsmith:hidden'], 'metadata': {'langgraph_step': 0, 'langgraph_node': '__start__', 'langgraph_triggers': ['__start__'], 'langgraph_path': ('__pregel_pull', '__start__'), 'langgraph_checkpoint_ns': '__start__:c814c808-4e66-2f9c-4a4b-67aea5ea7e46'}, 'parent_ids': ['8b70b221-ceba-40bc-abb5-44199db7154d']}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_start', 'data': {'input': {'messages': [AIMessage(content='So you said you were researching ocean mammals?', additional_kwargs={}, response_metadata={}, name='Bot', id='dcdce2ba-dfef-454b-8815-2beefb201928'), HumanMessage(content='Yes, I know about whales. But what others should I learn about?', additional_kwargs={}, response_metadata={}, name='Lance', id='314874d6-df07-4183-bb67-2aeded96d302')]}}, 'name': 'filter', 'tags': ['graph:step:1'], 'run_id': '380441c8-6bc3-40b3-b7b9-44baafa02f6d', 'metadata': {'langgraph_step': 1, 'langgraph_node': 'filter', 'langgraph_triggers': ['start:filter'], 'langgraph_path': ('__pregel_pull', 'filter'), 'langgraph_checkpoint_ns': 'filter:1d4aef83-aba4-7953-30ce-1b37c636bec4'}, 'parent_ids': ['8b70b221-ceba-40bc-abb5-44199db7154d']}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_start', 'data': {'input': {'messages': []}}, 'name': '_write', 'tags': ['seq:step:2', 'langsmith:hidden'], 'run_id': '8d5a79a1-8399-4e7b-aa1a-2a19f3063074', 'metadata': {'langgraph_step': 1, 'langgraph_node': 'filter', 'langgraph_triggers': ['start:filter'], 'langgraph_path': ('__pregel_pull', 'filter'), 'langgraph_checkpoint_ns': 'filter:1d4aef83-aba4-7953-30ce-1b37c636bec4'}, 'parent_ids': ['8b70b221-ceba-40bc-abb5-44199db7154d', '380441c8-6bc3-40b3-b7b9-44baafa02f6d']}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_end', 'data': {'output': {'messages': []}, 'input': {'messages': []}}, 'run_id': '8d5a79a1-8399-4e7b-aa1a-2a19f3063074', 'name': '_write', 'tags': ['seq:step:2', 'langsmith:hidden'], 'metadata': {'langgraph_step': 1, 'langgraph_node': 'filter', 'langgraph_triggers': ['start:filter'], 'langgraph_path': ('__pregel_pull', 'filter'), 'langgraph_checkpoint_ns': 'filter:1d4aef83-aba4-7953-30ce-1b37c636bec4'}, 'parent_ids': ['8b70b221-ceba-40bc-abb5-44199db7154d', '380441c8-6bc3-40b3-b7b9-44baafa02f6d']}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_stream', 'run_id': '380441c8-6bc3-40b3-b7b9-44baafa02f6d', 'name': 'filter', 'tags': ['graph:step:1'], 'metadata': {'langgraph_step': 1, 'langgraph_node': 'filter', 'langgraph_triggers': ['start:filter'], 'langgraph_path': ('__pregel_pull', 'filter'), 'langgraph_checkpoint_ns': 'filter:1d4aef83-aba4-7953-30ce-1b37c636bec4'}, 'data': {'chunk': {'messages': []}}, 'parent_ids': ['8b70b221-ceba-40bc-abb5-44199db7154d']}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_end', 'data': {'output': {'messages': []}, 'input': {'messages': [AIMessage(content='So you said you were researching ocean mammals?', additional_kwargs={}, response_metadata={}, name='Bot', id='dcdce2ba-dfef-454b-8815-2beefb201928'), HumanMessage(content='Yes, I know about whales. But what others should I learn about?', additional_kwargs={}, response_metadata={}, name='Lance', id='314874d6-df07-4183-bb67-2aeded96d302')]}}, 'run_id': '380441c8-6bc3-40b3-b7b9-44baafa02f6d', 'name': 'filter', 'tags': ['graph:step:1'], 'metadata': {'langgraph_step': 1, 'langgraph_node': 'filter', 'langgraph_triggers': ['start:filter'], 'langgraph_path': ('__pregel_pull', 'filter'), 'langgraph_checkpoint_ns': 'filter:1d4aef83-aba4-7953-30ce-1b37c636bec4'}, 'parent_ids': ['8b70b221-ceba-40bc-abb5-44199db7154d']}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_stream', 'run_id': '8b70b221-ceba-40bc-abb5-44199db7154d', 'name': 'LangGraph', 'tags': [], 'metadata': {}, 'data': {'chunk': {'filter': {'messages': []}}}, 'parent_ids': []}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_start', 'data': {'input': {'messages': [AIMessage(content='So you said you were researching ocean mammals?', additional_kwargs={}, response_metadata={}, name='Bot', id='dcdce2ba-dfef-454b-8815-2beefb201928'), HumanMessage(content='Yes, I know about whales. But what others should I learn about?', additional_kwargs={}, response_metadata={}, name='Lance', id='314874d6-df07-4183-bb67-2aeded96d302')]}}, 'name': 'chat_model', 'tags': ['graph:step:2'], 'run_id': 'ef2cdea1-641e-40d8-899a-64184ecb26a5', 'metadata': {'langgraph_step': 2, 'langgraph_node': 'chat_model', 'langgraph_triggers': ['filter'], 'langgraph_path': ('__pregel_pull', 'chat_model'), 'langgraph_checkpoint_ns': 'chat_model:6654d4e2-a56a-db5e-0343-6d3420d2857a'}, 'parent_ids': ['8b70b221-ceba-40bc-abb5-44199db7154d']}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_start', 'data': {'input': {'messages': [AIMessage(content='That\\'s great! Whales are fascinating creatures. Here are some other ocean mammals you might find interesting to learn about:\\n\\n**Pinnipeds:** \\n* **Seals:** There are many types of seals, including harbor seals, grey seals, and elephant seals. They are known for their sleek bodies and flippers.\\n* **Sea Lions:** These are larger than seals and have external ear flaps. They are also known for their loud barks.\\n* **Walruses:** These are massive animals with tusks and thick blubber. They use their tusks to dig for food and to defend themselves.\\n\\n**Sirenians:**\\n* **Manatees:** These gentle giants are herbivores and live in shallow, warm waters. They are often called \"sea cows\" because of their diet.\\n* **Dugongs:** These are closely related to manatees but have a different tail shape. They are found in the Indo-Pacific region.\\n\\n**Other:**\\n* **Polar Bears:** Although they spend much of their time on land, they are considered marine mammals because they rely on the ocean for food.\\n* **Sea Otters:** These are the smallest marine mammals and are known for their thick fur. They are found in the Pacific Ocean.\\n* **Dolphins:** These are highly intelligent animals and are known for their playful behavior. There are many different species of dolphins.\\n* **Porpoises:** These are smaller than dolphins and have a more blunt snout. They are often mistaken for dolphins.\\n\\n**Here are some resources you might find helpful:**\\n\\n* **Ocean Conservancy:** [https://oceanconservancy.org/](https://oceanconservancy.org/)\\n* **National Oceanic and Atmospheric Administration (NOAA):** [https://www.noaa.gov/](https://www.noaa.gov/)\\n* **World Wildlife Fund (WWF):** [https://www.worldwildlife.org/](https://www.worldwildlife.org/)\\n\\nI hope this helps! Let me know if you have any other questions. \\n', additional_kwargs={}, response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'safety_ratings': [{'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', 'probability': 'NEGLIGIBLE', 'blocked': False}]}, id='run-24cdced1-9034-46e8-9d08-cbcb237398af-0', usage_metadata={'input_tokens': 26, 'output_tokens': 422, 'total_tokens': 448})]}}, 'name': '_write', 'tags': ['seq:step:2', 'langsmith:hidden'], 'run_id': '651f1dd9-11e5-4e6f-86dd-e71d58c34d3f', 'metadata': {'langgraph_step': 2, 'langgraph_node': 'chat_model', 'langgraph_triggers': ['filter'], 'langgraph_path': ('__pregel_pull', 'chat_model'), 'langgraph_checkpoint_ns': 'chat_model:6654d4e2-a56a-db5e-0343-6d3420d2857a'}, 'parent_ids': ['8b70b221-ceba-40bc-abb5-44199db7154d', 'ef2cdea1-641e-40d8-899a-64184ecb26a5']}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_end', 'data': {'output': {'messages': [AIMessage(content='That\\'s great! Whales are fascinating creatures. Here are some other ocean mammals you might find interesting to learn about:\\n\\n**Pinnipeds:** \\n* **Seals:** There are many types of seals, including harbor seals, grey seals, and elephant seals. They are known for their sleek bodies and flippers.\\n* **Sea Lions:** These are larger than seals and have external ear flaps. They are also known for their loud barks.\\n* **Walruses:** These are massive animals with tusks and thick blubber. They use their tusks to dig for food and to defend themselves.\\n\\n**Sirenians:**\\n* **Manatees:** These gentle giants are herbivores and live in shallow, warm waters. They are often called \"sea cows\" because of their diet.\\n* **Dugongs:** These are closely related to manatees but have a different tail shape. They are found in the Indo-Pacific region.\\n\\n**Other:**\\n* **Polar Bears:** Although they spend much of their time on land, they are considered marine mammals because they rely on the ocean for food.\\n* **Sea Otters:** These are the smallest marine mammals and are known for their thick fur. They are found in the Pacific Ocean.\\n* **Dolphins:** These are highly intelligent animals and are known for their playful behavior. There are many different species of dolphins.\\n* **Porpoises:** These are smaller than dolphins and have a more blunt snout. They are often mistaken for dolphins.\\n\\n**Here are some resources you might find helpful:**\\n\\n* **Ocean Conservancy:** [https://oceanconservancy.org/](https://oceanconservancy.org/)\\n* **National Oceanic and Atmospheric Administration (NOAA):** [https://www.noaa.gov/](https://www.noaa.gov/)\\n* **World Wildlife Fund (WWF):** [https://www.worldwildlife.org/](https://www.worldwildlife.org/)\\n\\nI hope this helps! Let me know if you have any other questions. \\n', additional_kwargs={}, response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'safety_ratings': [{'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', 'probability': 'NEGLIGIBLE', 'blocked': False}]}, id='run-24cdced1-9034-46e8-9d08-cbcb237398af-0', usage_metadata={'input_tokens': 26, 'output_tokens': 422, 'total_tokens': 448})]}, 'input': {'messages': [AIMessage(content='That\\'s great! Whales are fascinating creatures. Here are some other ocean mammals you might find interesting to learn about:\\n\\n**Pinnipeds:** \\n* **Seals:** There are many types of seals, including harbor seals, grey seals, and elephant seals. They are known for their sleek bodies and flippers.\\n* **Sea Lions:** These are larger than seals and have external ear flaps. They are also known for their loud barks.\\n* **Walruses:** These are massive animals with tusks and thick blubber. They use their tusks to dig for food and to defend themselves.\\n\\n**Sirenians:**\\n* **Manatees:** These gentle giants are herbivores and live in shallow, warm waters. They are often called \"sea cows\" because of their diet.\\n* **Dugongs:** These are closely related to manatees but have a different tail shape. They are found in the Indo-Pacific region.\\n\\n**Other:**\\n* **Polar Bears:** Although they spend much of their time on land, they are considered marine mammals because they rely on the ocean for food.\\n* **Sea Otters:** These are the smallest marine mammals and are known for their thick fur. They are found in the Pacific Ocean.\\n* **Dolphins:** These are highly intelligent animals and are known for their playful behavior. There are many different species of dolphins.\\n* **Porpoises:** These are smaller than dolphins and have a more blunt snout. They are often mistaken for dolphins.\\n\\n**Here are some resources you might find helpful:**\\n\\n* **Ocean Conservancy:** [https://oceanconservancy.org/](https://oceanconservancy.org/)\\n* **National Oceanic and Atmospheric Administration (NOAA):** [https://www.noaa.gov/](https://www.noaa.gov/)\\n* **World Wildlife Fund (WWF):** [https://www.worldwildlife.org/](https://www.worldwildlife.org/)\\n\\nI hope this helps! Let me know if you have any other questions. \\n', additional_kwargs={}, response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'safety_ratings': [{'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', 'probability': 'NEGLIGIBLE', 'blocked': False}]}, id='run-24cdced1-9034-46e8-9d08-cbcb237398af-0', usage_metadata={'input_tokens': 26, 'output_tokens': 422, 'total_tokens': 448})]}}, 'run_id': '651f1dd9-11e5-4e6f-86dd-e71d58c34d3f', 'name': '_write', 'tags': ['seq:step:2', 'langsmith:hidden'], 'metadata': {'langgraph_step': 2, 'langgraph_node': 'chat_model', 'langgraph_triggers': ['filter'], 'langgraph_path': ('__pregel_pull', 'chat_model'), 'langgraph_checkpoint_ns': 'chat_model:6654d4e2-a56a-db5e-0343-6d3420d2857a'}, 'parent_ids': ['8b70b221-ceba-40bc-abb5-44199db7154d', 'ef2cdea1-641e-40d8-899a-64184ecb26a5']}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_stream', 'run_id': 'ef2cdea1-641e-40d8-899a-64184ecb26a5', 'name': 'chat_model', 'tags': ['graph:step:2'], 'metadata': {'langgraph_step': 2, 'langgraph_node': 'chat_model', 'langgraph_triggers': ['filter'], 'langgraph_path': ('__pregel_pull', 'chat_model'), 'langgraph_checkpoint_ns': 'chat_model:6654d4e2-a56a-db5e-0343-6d3420d2857a'}, 'data': {'chunk': {'messages': [AIMessage(content='That\\'s great! Whales are fascinating creatures. Here are some other ocean mammals you might find interesting to learn about:\\n\\n**Pinnipeds:** \\n* **Seals:** There are many types of seals, including harbor seals, grey seals, and elephant seals. They are known for their sleek bodies and flippers.\\n* **Sea Lions:** These are larger than seals and have external ear flaps. They are also known for their loud barks.\\n* **Walruses:** These are massive animals with tusks and thick blubber. They use their tusks to dig for food and to defend themselves.\\n\\n**Sirenians:**\\n* **Manatees:** These gentle giants are herbivores and live in shallow, warm waters. They are often called \"sea cows\" because of their diet.\\n* **Dugongs:** These are closely related to manatees but have a different tail shape. They are found in the Indo-Pacific region.\\n\\n**Other:**\\n* **Polar Bears:** Although they spend much of their time on land, they are considered marine mammals because they rely on the ocean for food.\\n* **Sea Otters:** These are the smallest marine mammals and are known for their thick fur. They are found in the Pacific Ocean.\\n* **Dolphins:** These are highly intelligent animals and are known for their playful behavior. There are many different species of dolphins.\\n* **Porpoises:** These are smaller than dolphins and have a more blunt snout. They are often mistaken for dolphins.\\n\\n**Here are some resources you might find helpful:**\\n\\n* **Ocean Conservancy:** [https://oceanconservancy.org/](https://oceanconservancy.org/)\\n* **National Oceanic and Atmospheric Administration (NOAA):** [https://www.noaa.gov/](https://www.noaa.gov/)\\n* **World Wildlife Fund (WWF):** [https://www.worldwildlife.org/](https://www.worldwildlife.org/)\\n\\nI hope this helps! Let me know if you have any other questions. \\n', additional_kwargs={}, response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'safety_ratings': [{'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', 'probability': 'NEGLIGIBLE', 'blocked': False}]}, id='run-24cdced1-9034-46e8-9d08-cbcb237398af-0', usage_metadata={'input_tokens': 26, 'output_tokens': 422, 'total_tokens': 448})]}}, 'parent_ids': ['8b70b221-ceba-40bc-abb5-44199db7154d']}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_end', 'data': {'output': {'messages': [AIMessage(content='That\\'s great! Whales are fascinating creatures. Here are some other ocean mammals you might find interesting to learn about:\\n\\n**Pinnipeds:** \\n* **Seals:** There are many types of seals, including harbor seals, grey seals, and elephant seals. They are known for their sleek bodies and flippers.\\n* **Sea Lions:** These are larger than seals and have external ear flaps. They are also known for their loud barks.\\n* **Walruses:** These are massive animals with tusks and thick blubber. They use their tusks to dig for food and to defend themselves.\\n\\n**Sirenians:**\\n* **Manatees:** These gentle giants are herbivores and live in shallow, warm waters. They are often called \"sea cows\" because of their diet.\\n* **Dugongs:** These are closely related to manatees but have a different tail shape. They are found in the Indo-Pacific region.\\n\\n**Other:**\\n* **Polar Bears:** Although they spend much of their time on land, they are considered marine mammals because they rely on the ocean for food.\\n* **Sea Otters:** These are the smallest marine mammals and are known for their thick fur. They are found in the Pacific Ocean.\\n* **Dolphins:** These are highly intelligent animals and are known for their playful behavior. There are many different species of dolphins.\\n* **Porpoises:** These are smaller than dolphins and have a more blunt snout. They are often mistaken for dolphins.\\n\\n**Here are some resources you might find helpful:**\\n\\n* **Ocean Conservancy:** [https://oceanconservancy.org/](https://oceanconservancy.org/)\\n* **National Oceanic and Atmospheric Administration (NOAA):** [https://www.noaa.gov/](https://www.noaa.gov/)\\n* **World Wildlife Fund (WWF):** [https://www.worldwildlife.org/](https://www.worldwildlife.org/)\\n\\nI hope this helps! Let me know if you have any other questions. \\n', additional_kwargs={}, response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'safety_ratings': [{'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', 'probability': 'NEGLIGIBLE', 'blocked': False}]}, id='run-24cdced1-9034-46e8-9d08-cbcb237398af-0', usage_metadata={'input_tokens': 26, 'output_tokens': 422, 'total_tokens': 448})]}, 'input': {'messages': [AIMessage(content='So you said you were researching ocean mammals?', additional_kwargs={}, response_metadata={}, name='Bot', id='dcdce2ba-dfef-454b-8815-2beefb201928'), HumanMessage(content='Yes, I know about whales. But what others should I learn about?', additional_kwargs={}, response_metadata={}, name='Lance', id='314874d6-df07-4183-bb67-2aeded96d302')]}}, 'run_id': 'ef2cdea1-641e-40d8-899a-64184ecb26a5', 'name': 'chat_model', 'tags': ['graph:step:2'], 'metadata': {'langgraph_step': 2, 'langgraph_node': 'chat_model', 'langgraph_triggers': ['filter'], 'langgraph_path': ('__pregel_pull', 'chat_model'), 'langgraph_checkpoint_ns': 'chat_model:6654d4e2-a56a-db5e-0343-6d3420d2857a'}, 'parent_ids': ['8b70b221-ceba-40bc-abb5-44199db7154d']}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_stream', 'run_id': '8b70b221-ceba-40bc-abb5-44199db7154d', 'name': 'LangGraph', 'tags': [], 'metadata': {}, 'data': {'chunk': {'chat_model': {'messages': [AIMessage(content='That\\'s great! Whales are fascinating creatures. Here are some other ocean mammals you might find interesting to learn about:\\n\\n**Pinnipeds:** \\n* **Seals:** There are many types of seals, including harbor seals, grey seals, and elephant seals. They are known for their sleek bodies and flippers.\\n* **Sea Lions:** These are larger than seals and have external ear flaps. They are also known for their loud barks.\\n* **Walruses:** These are massive animals with tusks and thick blubber. They use their tusks to dig for food and to defend themselves.\\n\\n**Sirenians:**\\n* **Manatees:** These gentle giants are herbivores and live in shallow, warm waters. They are often called \"sea cows\" because of their diet.\\n* **Dugongs:** These are closely related to manatees but have a different tail shape. They are found in the Indo-Pacific region.\\n\\n**Other:**\\n* **Polar Bears:** Although they spend much of their time on land, they are considered marine mammals because they rely on the ocean for food.\\n* **Sea Otters:** These are the smallest marine mammals and are known for their thick fur. They are found in the Pacific Ocean.\\n* **Dolphins:** These are highly intelligent animals and are known for their playful behavior. There are many different species of dolphins.\\n* **Porpoises:** These are smaller than dolphins and have a more blunt snout. They are often mistaken for dolphins.\\n\\n**Here are some resources you might find helpful:**\\n\\n* **Ocean Conservancy:** [https://oceanconservancy.org/](https://oceanconservancy.org/)\\n* **National Oceanic and Atmospheric Administration (NOAA):** [https://www.noaa.gov/](https://www.noaa.gov/)\\n* **World Wildlife Fund (WWF):** [https://www.worldwildlife.org/](https://www.worldwildlife.org/)\\n\\nI hope this helps! Let me know if you have any other questions. \\n', additional_kwargs={}, response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'safety_ratings': [{'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', 'probability': 'NEGLIGIBLE', 'blocked': False}]}, id='run-24cdced1-9034-46e8-9d08-cbcb237398af-0', usage_metadata={'input_tokens': 26, 'output_tokens': 422, 'total_tokens': 448})]}}}, 'parent_ids': []}\n",
            "\n",
            "--------------\n",
            "\n",
            "{'event': 'on_chain_end', 'data': {'output': {'messages': [AIMessage(content='So you said you were researching ocean mammals?', additional_kwargs={}, response_metadata={}, name='Bot', id='dcdce2ba-dfef-454b-8815-2beefb201928'), HumanMessage(content='Yes, I know about whales. But what others should I learn about?', additional_kwargs={}, response_metadata={}, name='Lance', id='314874d6-df07-4183-bb67-2aeded96d302'), AIMessage(content='That\\'s great! Whales are fascinating creatures. Here are some other ocean mammals you might find interesting to learn about:\\n\\n**Pinnipeds:** \\n* **Seals:** There are many types of seals, including harbor seals, grey seals, and elephant seals. They are known for their sleek bodies and flippers.\\n* **Sea Lions:** These are larger than seals and have external ear flaps. They are also known for their loud barks.\\n* **Walruses:** These are massive animals with tusks and thick blubber. They use their tusks to dig for food and to defend themselves.\\n\\n**Sirenians:**\\n* **Manatees:** These gentle giants are herbivores and live in shallow, warm waters. They are often called \"sea cows\" because of their diet.\\n* **Dugongs:** These are closely related to manatees but have a different tail shape. They are found in the Indo-Pacific region.\\n\\n**Other:**\\n* **Polar Bears:** Although they spend much of their time on land, they are considered marine mammals because they rely on the ocean for food.\\n* **Sea Otters:** These are the smallest marine mammals and are known for their thick fur. They are found in the Pacific Ocean.\\n* **Dolphins:** These are highly intelligent animals and are known for their playful behavior. There are many different species of dolphins.\\n* **Porpoises:** These are smaller than dolphins and have a more blunt snout. They are often mistaken for dolphins.\\n\\n**Here are some resources you might find helpful:**\\n\\n* **Ocean Conservancy:** [https://oceanconservancy.org/](https://oceanconservancy.org/)\\n* **National Oceanic and Atmospheric Administration (NOAA):** [https://www.noaa.gov/](https://www.noaa.gov/)\\n* **World Wildlife Fund (WWF):** [https://www.worldwildlife.org/](https://www.worldwildlife.org/)\\n\\nI hope this helps! Let me know if you have any other questions. \\n', additional_kwargs={}, response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'safety_ratings': [{'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HATE_SPEECH', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_HARASSMENT', 'probability': 'NEGLIGIBLE', 'blocked': False}, {'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', 'probability': 'NEGLIGIBLE', 'blocked': False}]}, id='run-24cdced1-9034-46e8-9d08-cbcb237398af-0', usage_metadata={'input_tokens': 26, 'output_tokens': 422, 'total_tokens': 448})]}}, 'run_id': '8b70b221-ceba-40bc-abb5-44199db7154d', 'name': 'LangGraph', 'tags': [], 'metadata': {}, 'parent_ids': []}\n",
            "\n",
            "--------------\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "id": "34c33e63-1ef4-412d-bb10-6a1b9e5b35a7",
      "metadata": {
        "id": "34c33e63-1ef4-412d-bb10-6a1b9e5b35a7"
      },
      "source": [
        "## Reducer\n",
        "\n",
        "A practical challenge when working with messages is managing long-running conversations.\n",
        "\n",
        "Long-running conversations result in high token usage and latency if we are not careful, because we pass a growing list of messages to the model.\n",
        "\n",
        "We have a few ways to address this.\n",
        "\n",
        "First, recall the trick we saw using `RemoveMessage` and the `add_messages` reducer."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 26,
      "id": "222c6bc5-bb0e-4a43-80f5-c8ec38d99f3a",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 350
        },
        "id": "222c6bc5-bb0e-4a43-80f5-c8ec38d99f3a",
        "outputId": "fb6b40c3-70d0-46e8-9d74-3389837cafbd"
      },
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "image/jpeg": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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2UYnbswt3uO4xOcGnmimidyywu1rmY7zH+wjoQR0UyivBHFLiUUDo0DD7pwVyOjmIttdb7pT+b3Y59NKB85a17XH59N/EuA8KMx2dUNtI/L3fVrf0Xah7Z0pKjo/TpQm7IwDxUZl+A232931aeKjMvwG2+3u+rW/orfrWk5Lg+ouyMA8VGZfgNt9vd9WniozL8Btvt7vq1v6J+taTkuD6i7IwDxUZl+A232931a99Nwey6qla2U2mgiP20pqJJnj8TAxoP/uC3hFD7a0p4U4f2Lsin4Tw0t+HPNUZX3G6ObyurJwByA97Y2joxp185PnJ0FcERcabNjnxuOY6sgIiLEAiIgP/Z\n",
            "text/plain": [
              "<IPython.core.display.Image object>"
            ]
          },
          "metadata": {}
        }
      ],
      "source": [
        "from langchain_core.messages import RemoveMessage\n",
        "\n",
        "# Nodes\n",
        "def filter_messages(state: MessagesState) -> MessagesState:\n",
        "    # Delete all but the 2 most recent messages\n",
        "    delete_messages = [RemoveMessage(id=m.id) for m in state[\"messages\"][:-2]]\n",
        "    return {\"messages\": delete_messages}\n",
        "\n",
        "def chat_model_node(state: MessagesState) -> MessagesState:\n",
        "    return {\"messages\": [llm.invoke(state[\"messages\"])]}\n",
        "\n",
        "# Build graph\n",
        "builder: StateGraph = StateGraph(MessagesState)\n",
        "builder.add_node(\"filter\", filter_messages)\n",
        "builder.add_node(\"chat_model\", chat_model_node)\n",
        "builder.add_edge(START, \"filter\")\n",
        "builder.add_edge(\"filter\", \"chat_model\")\n",
        "builder.add_edge(\"chat_model\", END)\n",
        "graph: CompiledStateGraph = builder.compile()\n",
        "\n",
        "# View\n",
        "display(Image(graph.get_graph().draw_mermaid_png()))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 27,
      "id": "95a7c2cc-54ce-43e7-9a90-abf37827d709",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "95a7c2cc-54ce-43e7-9a90-abf37827d709",
        "outputId": "0324a3ed-1934-45db-f71b-725662ba5f9b"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
            "Name: Bot\n",
            "\n",
            "So you said you were researching ocean mammals?\n",
            "================================\u001b[1m Human Message \u001b[0m=================================\n",
            "Name: Lance\n",
            "\n",
            "Yes, I know about whales. But what others should I learn about?\n",
            "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
            "\n",
            "That's great! Whales are fascinating creatures.  But the world of ocean mammals goes way beyond whales! Here are some others to dive into:\n",
            "\n",
            "**Marine Mammals:**\n",
            "\n",
            "* **Dolphins:** These intelligent and social creatures are found in all oceans.  There are over 40 different species, each with unique characteristics and behaviors.\n",
            "* **Porpoises:**  Often confused with dolphins, porpoises are smaller, stockier, and have a triangular dorsal fin.\n",
            "* **Seals:**  These pinnipeds (meaning \"fin-footed\") spend most of their time in the water but come ashore to rest and breed.  There are two main types:  **true seals** (like harbor seals) and **eared seals** (like fur seals and sea lions).\n",
            "* **Sea Lions:**   They are the largest of the eared seals and are known for their playful and acrobatic nature.\n",
            "* **Walruses:**  These massive animals have distinctive tusks and spend their time foraging on the ocean floor for clams and other invertebrates.\n",
            "* **Manatees:** Also known as \"sea cows,\" these gentle giants are herbivores that graze on seagrass in warm, shallow waters.\n",
            "* **Sea Otters:**  The smallest marine mammal in North America, sea otters are known for their thick fur and playful personalities.\n",
            "\n",
            "**Beyond the Basics:**\n",
            "\n",
            "* **Polar Bears:** While they spend much of their time on land, polar bears are highly adapted to life in the Arctic ice and are expert swimmers.\n",
            "* **Sea Otters:**  The smallest marine mammal in North America, sea otters are known for their thick fur and playful personalities.\n",
            "* **Dugsongs:**   These large, migratory marine mammals are found in the northern hemisphere and are known for their complex songs.\n",
            "\n",
            "**Getting Started:**\n",
            "\n",
            "* **Research online:**  Websites like National Geographic, NOAA, and WWF offer great resources on ocean mammals.\n",
            "* **Visit a local aquarium:**  Many aquariums have exhibits that showcase the diversity of marine mammals.\n",
            "* **Read books:**  There are many excellent books about ocean mammals, both for adults and children.\n",
            "\n",
            "I hope this gives you a good starting point for your research!  What are you most interested in learning about?  I'm happy to help you find more information.\n"
          ]
        }
      ],
      "source": [
        "# Message list with a preamble\n",
        "messages = [AIMessage(\"Hi.\", name=\"Bot\", id=\"1\")]\n",
        "messages.append(HumanMessage(\"Hi.\", name=\"Lance\", id=\"2\"))\n",
        "messages.append(AIMessage(\"So you said you were researching ocean mammals?\", name=\"Bot\", id=\"3\"))\n",
        "messages.append(HumanMessage(\"Yes, I know about whales. But what others should I learn about?\", name=\"Lance\", id=\"4\"))\n",
        "\n",
        "# Invoke\n",
        "output = graph.invoke({'messages': messages})\n",
        "for m in output['messages']:\n",
        "    m.pretty_print()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f506457d-014b-4fee-a684-e5edfb4b8f0d",
      "metadata": {
        "id": "f506457d-014b-4fee-a684-e5edfb4b8f0d"
      },
      "source": [
        "## Filtering messages\n",
        "\n",
        "If you don't need or want to modify the graph state, you can just filter the messages you pass to the chat model.\n",
        "\n",
        "For example, just pass in a filtered list: `llm.invoke(messages[-1:])` to the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 28,
      "id": "22d0b904-7cd6-486b-8948-105bee3d4683",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 251
        },
        "id": "22d0b904-7cd6-486b-8948-105bee3d4683",
        "outputId": "f429d516-5ace-4986-bbe6-1b842fd3ebf4"
      },
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "image/jpeg": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAAB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6IjCCFBltJHUEIHSs1JmK3fsg5a1zgPCW3jFxnrHoTrg4tok96EJQ1+zmbWf86zjEcUl59LLMJS2bclXLJuaAOVv40Nk9FOd46bCe9XqSr0RbbdGtFvjQYbSWIkZtLTTSe5CUjQH7BXO9NZVAoM3hel36i60I7NKUrjgKUpQClKUApSlAVS98LMVyCUuTLs7SZLh5nH4i1xnHD8alNKSVH6zuo1XA/EVKJMWfs9el1lD/APSr7StuHLMpgVmGZEltZNWUH4DcR+Sz/wB7S/e0+A3Efks/97S/e1fqVfPsq+rFvYqyg/AbiPyWf+9pfvafAbiPyWf+9pfvav1KZ9lX1Yt7FWUH4DcR+Sz/AN7S/e1zxuC+HRng4q0GWR+hOlPSUH7UOLUk/sq70qHluVNUc2LexVnwww3GZQ0y2lppCQlCEJASkDuAA7hX3SlaRApSlAKUpQH/2Q==\n",
            "text/plain": [
              "<IPython.core.display.Image object>"
            ]
          },
          "metadata": {}
        }
      ],
      "source": [
        "# Node\n",
        "def chat_model_node(state: MessagesState):\n",
        "    return {\"messages\": [llm.invoke(state[\"messages\"][-1:])]}\n",
        "\n",
        "# Build graph\n",
        "builder: StateGraph = StateGraph(MessagesState)\n",
        "builder.add_node(\"chat_model\", chat_model_node)\n",
        "builder.add_edge(START, \"chat_model\")\n",
        "builder.add_edge(\"chat_model\", END)\n",
        "graph: CompiledStateGraph = builder.compile()\n",
        "\n",
        "# View\n",
        "display(Image(graph.get_graph().draw_mermaid_png()))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "6f58c6fc-532f-418d-b70a-cfcb3307daf5",
      "metadata": {
        "id": "6f58c6fc-532f-418d-b70a-cfcb3307daf5"
      },
      "source": [
        "Let's take our existing list of messages, append the above LLM response, and append a follow-up question."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 29,
      "id": "16956015-1dbe-4108-89b5-4209b68b51ca",
      "metadata": {
        "id": "16956015-1dbe-4108-89b5-4209b68b51ca"
      },
      "outputs": [],
      "source": [
        "messages.append(output['messages'][-1])\n",
        "messages.append(HumanMessage(f\"Tell me more about Narwhals!\", name=\"Lance\"))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 30,
      "id": "85563415-c085-46a8-a4ac-155df798c54e",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "85563415-c085-46a8-a4ac-155df798c54e",
        "outputId": "7e3dffce-bda8-4e12-fa63-545bc0f5cd1e"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
            "Name: Bot\n",
            "\n",
            "Hi.\n",
            "================================\u001b[1m Human Message \u001b[0m=================================\n",
            "Name: Lance\n",
            "\n",
            "Hi.\n",
            "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
            "Name: Bot\n",
            "\n",
            "So you said you were researching ocean mammals?\n",
            "================================\u001b[1m Human Message \u001b[0m=================================\n",
            "Name: Lance\n",
            "\n",
            "Yes, I know about whales. But what others should I learn about?\n",
            "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
            "\n",
            "That's great! Whales are fascinating creatures.  But the world of ocean mammals goes way beyond whales! Here are some others to dive into:\n",
            "\n",
            "**Marine Mammals:**\n",
            "\n",
            "* **Dolphins:** These intelligent and social creatures are found in all oceans.  There are over 40 different species, each with unique characteristics and behaviors.\n",
            "* **Porpoises:**  Often confused with dolphins, porpoises are smaller, stockier, and have a triangular dorsal fin.\n",
            "* **Seals:**  These pinnipeds (meaning \"fin-footed\") spend most of their time in the water but come ashore to rest and breed.  There are two main types:  **true seals** (like harbor seals) and **eared seals** (like fur seals and sea lions).\n",
            "* **Sea Lions:**   They are the largest of the eared seals and are known for their playful and acrobatic nature.\n",
            "* **Walruses:**  These massive animals have distinctive tusks and spend their time foraging on the ocean floor for clams and other invertebrates.\n",
            "* **Manatees:** Also known as \"sea cows,\" these gentle giants are herbivores that graze on seagrass in warm, shallow waters.\n",
            "* **Sea Otters:**  The smallest marine mammal in North America, sea otters are known for their thick fur and playful personalities.\n",
            "\n",
            "**Beyond the Basics:**\n",
            "\n",
            "* **Polar Bears:** While they spend much of their time on land, polar bears are highly adapted to life in the Arctic ice and are expert swimmers.\n",
            "* **Sea Otters:**  The smallest marine mammal in North America, sea otters are known for their thick fur and playful personalities.\n",
            "* **Dugsongs:**   These large, migratory marine mammals are found in the northern hemisphere and are known for their complex songs.\n",
            "\n",
            "**Getting Started:**\n",
            "\n",
            "* **Research online:**  Websites like National Geographic, NOAA, and WWF offer great resources on ocean mammals.\n",
            "* **Visit a local aquarium:**  Many aquariums have exhibits that showcase the diversity of marine mammals.\n",
            "* **Read books:**  There are many excellent books about ocean mammals, both for adults and children.\n",
            "\n",
            "I hope this gives you a good starting point for your research!  What are you most interested in learning about?  I'm happy to help you find more information.\n",
            "================================\u001b[1m Human Message \u001b[0m=================================\n",
            "Name: Lance\n",
            "\n",
            "Tell me more about Narwhals!\n"
          ]
        }
      ],
      "source": [
        "for m in messages:\n",
        "    m.pretty_print()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 31,
      "id": "23349705-a059-47b5-9760-d8f64e687393",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "23349705-a059-47b5-9760-d8f64e687393",
        "outputId": "9065d0c3-08e7-47f3-a695-0d56b16bf34d"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
            "Name: Bot\n",
            "\n",
            "Hi.\n",
            "================================\u001b[1m Human Message \u001b[0m=================================\n",
            "Name: Lance\n",
            "\n",
            "Hi.\n",
            "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
            "Name: Bot\n",
            "\n",
            "So you said you were researching ocean mammals?\n",
            "================================\u001b[1m Human Message \u001b[0m=================================\n",
            "Name: Lance\n",
            "\n",
            "Yes, I know about whales. But what others should I learn about?\n",
            "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
            "\n",
            "That's great! Whales are fascinating creatures.  But the world of ocean mammals goes way beyond whales! Here are some others to dive into:\n",
            "\n",
            "**Marine Mammals:**\n",
            "\n",
            "* **Dolphins:** These intelligent and social creatures are found in all oceans.  There are over 40 different species, each with unique characteristics and behaviors.\n",
            "* **Porpoises:**  Often confused with dolphins, porpoises are smaller, stockier, and have a triangular dorsal fin.\n",
            "* **Seals:**  These pinnipeds (meaning \"fin-footed\") spend most of their time in the water but come ashore to rest and breed.  There are two main types:  **true seals** (like harbor seals) and **eared seals** (like fur seals and sea lions).\n",
            "* **Sea Lions:**   They are the largest of the eared seals and are known for their playful and acrobatic nature.\n",
            "* **Walruses:**  These massive animals have distinctive tusks and spend their time foraging on the ocean floor for clams and other invertebrates.\n",
            "* **Manatees:** Also known as \"sea cows,\" these gentle giants are herbivores that graze on seagrass in warm, shallow waters.\n",
            "* **Sea Otters:**  The smallest marine mammal in North America, sea otters are known for their thick fur and playful personalities.\n",
            "\n",
            "**Beyond the Basics:**\n",
            "\n",
            "* **Polar Bears:** While they spend much of their time on land, polar bears are highly adapted to life in the Arctic ice and are expert swimmers.\n",
            "* **Sea Otters:**  The smallest marine mammal in North America, sea otters are known for their thick fur and playful personalities.\n",
            "* **Dugsongs:**   These large, migratory marine mammals are found in the northern hemisphere and are known for their complex songs.\n",
            "\n",
            "**Getting Started:**\n",
            "\n",
            "* **Research online:**  Websites like National Geographic, NOAA, and WWF offer great resources on ocean mammals.\n",
            "* **Visit a local aquarium:**  Many aquariums have exhibits that showcase the diversity of marine mammals.\n",
            "* **Read books:**  There are many excellent books about ocean mammals, both for adults and children.\n",
            "\n",
            "I hope this gives you a good starting point for your research!  What are you most interested in learning about?  I'm happy to help you find more information.\n",
            "================================\u001b[1m Human Message \u001b[0m=================================\n",
            "Name: Lance\n",
            "\n",
            "Tell me more about Narwhals!\n",
            "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
            "\n",
            "## Narwhals: The Unicorns of the Arctic\n",
            "\n",
            "Narwhals are truly fascinating creatures! They are a type of toothed whale that inhabit the Arctic waters around Greenland, Canada, and Russia. Here's a closer look at these enigmatic creatures:\n",
            "\n",
            "**Distinctive Features:**\n",
            "\n",
            "* **The Tusk:** The most striking feature of the narwhal is its long, spiraled tusk, which is actually a modified upper left canine tooth. Only males have this tusk, which can grow up to 10 feet long and weigh up to 20 pounds. \n",
            "* **The Purpose of the Tusk:**  The exact purpose of the tusk is still debated, but it is believed to be used for:\n",
            "    * **Sensory organ:**  The tusk is covered in sensory receptors, making it a potential tool for sensing changes in temperature, salinity, and pressure.\n",
            "    * **Social display:**  The tusk may be used in mating rituals or to establish dominance.\n",
            "    * **Fighting:**  The tusk may be used for combat, but this is less likely as it is quite fragile.\n",
            "* **Appearance:**  Narwhals are medium-sized whales, reaching up to 16 feet in length. They have a slender body, a small dorsal fin, and a distinctive \"melon\" on their forehead. Their skin is mottled gray or brown.\n",
            "\n",
            "**Behavior and Ecology:**\n",
            "\n",
            "* **Social Animals:**  Narwhals are social animals, living in groups of up to 100 individuals. \n",
            "* **Diving Champions:**  They are deep divers, capable of reaching depths of over 1,500 meters (nearly a mile!) to hunt for food. \n",
            "* **Diet:**  Their diet consists mainly of fish, squid, and other marine invertebrates.\n",
            "* **Migration:**  Narwhals migrate seasonally, following the movement of their prey.\n",
            "\n",
            "**Conservation Status:**\n",
            "\n",
            "* **Near Threatened:**  Narwhals are listed as \"Near Threatened\" by the IUCN due to threats like climate change, hunting, and pollution. \n",
            "* **Importance:**  Narwhals play a crucial role in the Arctic ecosystem, and their conservation is important for the health of the entire region.\n",
            "\n",
            "**Fun Facts:**\n",
            "\n",
            "* **The Queen of the Arctic:**  The tusk was once believed to be the horn of a mythical creature, and it was highly prized by royalty and wealthy individuals. \n",
            "* **The \"Narwhal\" Name:**  The name \"narwhal\" comes from the Old Norse word \"narhvalr,\" which means \"corpse whale.\" This is likely because the narwhal's tusk resembles a long, spiraled horn.\n",
            "* **The \"Unicorn\" of the Sea:**  The narwhal's tusk has given it the nickname \"the unicorn of the sea.\"\n",
            "\n",
            "**If you're interested in learning more about these fascinating creatures, I recommend checking out the following resources:**\n",
            "\n",
            "* **The World Wildlife Fund (WWF):** https://www.worldwildlife.org/species/narwhal\n",
            "* **The National Oceanic and Atmospheric Administration (NOAA):** https://www.fisheries.noaa.gov/species/narwhal\n",
            "* **The Ocean Conservancy:** https://oceanconservancy.org/blog/2018/04/12/narwhals-the-unicorns-of-the-sea/\n",
            "\n",
            "I hope this information has been helpful!\n"
          ]
        }
      ],
      "source": [
        "# Invoke, using message filtering\n",
        "output = graph.invoke({'messages': messages})\n",
        "for m in output['messages']:\n",
        "    m.pretty_print()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "42e1d8d2-e297-4d78-b54c-d12b3c866745",
      "metadata": {
        "id": "42e1d8d2-e297-4d78-b54c-d12b3c866745"
      },
      "source": [
        "The state has all of the mesages.\n",
        "\n",
        "But, let's look at the LangSmith trace to see that the model invocation only uses the last message:\n",
        "\n",
        "https://smith.langchain.com/public/75aca3ce-ef19-4b92-94be-0178c7a660d9/r"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "fc40d930-3c1f-47fe-8d2a-ce174873353c",
      "metadata": {
        "id": "fc40d930-3c1f-47fe-8d2a-ce174873353c"
      },
      "source": [
        "## Trim messages\n",
        "\n",
        "Another approach is to [trim messages](https://python.langchain.com/v0.2/docs/how_to/trim_messages/#getting-the-last-max_tokens-tokens), based upon a set number of tokens.\n",
        "\n",
        "This restricts the message history to a specified number of tokens.\n",
        "\n",
        "While filtering only returns a post-hoc subset of the messages between agents, trimming restricts the number of tokens that a chat model can use to respond.\n",
        "\n",
        "See the `trim_messages` below."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 32,
      "id": "2ff99b81-cf03-4cc2-b44f-44829a73e1fd",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 251
        },
        "id": "2ff99b81-cf03-4cc2-b44f-44829a73e1fd",
        "outputId": "dd032e1c-87f5-47a8-f9d4-dbe4541441a6"
      },
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "image/jpeg": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyWFlaAAABFAAAABRnWFlaAAABKAAAABRiWFlaAAABPAAAABR3dHB0AAABUAAAABRyVFJDAAABZAAAAChnVFJDAAABZAAAAChiVFJDAAABZAAAAChjcHJ0AAABjAAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAAgAAAAcAHMAUgBHAEJYWVogAAAAAAAAb6IAADj1AAADkFhZWiAAAAAAAABimQAAt4UAABjaWFlaIAAAAAAAACSgAAAPhAAAts9YWVogAAAAAAAA9tYAAQAAAADTLXBhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAAABtbHVjAAAAAAAAAAEAAAAMZW5VUwAAACAAAAAcAEcAbwBvAGcAbABlACAASQBuAGMALgAgADIAMAAxADb/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCADqAIIDASIAAhEBAxEB/8QAHQABAAMAAwEBAQAAAAAAAAAAAAUGBwMECAIBCf/EAEwQAAEDBAADAggICggFBQAAAAECAwQABQYRBxIhEzEIFBUWIkGU0xdRVFVWYXHRIzI0NkJ0kZWxsjNEUnJ1gZKTJENTodIJGFeiw//EABoBAQACAwEAAAAAAAAAAAAAAAABAgMEBg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vNowKFiMoZHbpb8OK7H51xmHkrLjikaTtILmkgqOu7qdVszbDbO+zbSjffygDdfda7yaGJuKK933bNbu1gxniJwvvuWX3N3oTTTSZtutZgPPuJ7N6RGkOPFtQB5gD6A2Rr0vXo12YUy+u8SYWX5RYm8OssCySIb8mdc460JdcfYUkFSVdEnlOif89dN67X4tCXElKkhST3gjYqXkyraTf8ANv5YKoOLmCqOhmmPH19Lqx/51zQ+KGG3GWzFiZbYpUp9YbaYZuTK1uLJ0EpSFbJJ6ACrB4jG+Ttf6BX6IjCCFBltJHUEIHSs1JmK3fsg5a1zgPCW3jFxnrHoTrg4tok96EJQ1+zmbWf86zjEcUl59LLMJS2bclXLJuaAOVv40Nk9FOd46bCe9XqSr0RbbdGtFvjQYbSWIkZtLTTSe5CUjQH7BXO9NZVAoM3hel36i60I7NKUrjgKUpQClKUApSlAVS98LMVyCUuTLs7SZLh5nH4i1xnHD8alNKSVH6zuo1XA/EVKJMWfs9el1lD/APSr7StuHLMpgVmGZEltZNWUH4DcR+Sz/wB7S/e0+A3Efks/97S/e1fqVfPsq+rFvYqyg/AbiPyWf+9pfvafAbiPyWf+9pfvav1KZ9lX1Yt7FWUH4DcR+Sz/AN7S/e1zxuC+HRng4q0GWR+hOlPSUH7UOLUk/sq70qHluVNUc2LexVnwww3GZQ0y2lppCQlCEJASkDuAA7hX3SlaRApSlAKUpQH/2Q==\n",
            "text/plain": [
              "<IPython.core.display.Image object>"
            ]
          },
          "metadata": {}
        }
      ],
      "source": [
        "from langchain_core.messages import trim_messages\n",
        "\n",
        "# Node\n",
        "def chat_model_node(state: MessagesState):\n",
        "    messages = trim_messages(\n",
        "            state[\"messages\"],\n",
        "            max_tokens=100,\n",
        "            strategy=\"last\",\n",
        "            token_counter=ChatGoogleGenerativeAI(model=\"gemini-1.5-flash\"),\n",
        "            allow_partial=False,\n",
        "        )\n",
        "    return {\"messages\": [llm.invoke(messages)]}\n",
        "\n",
        "# Build graph\n",
        "builder = StateGraph(MessagesState)\n",
        "builder.add_node(\"chat_model\", chat_model_node)\n",
        "builder.add_edge(START, \"chat_model\")\n",
        "builder.add_edge(\"chat_model\", END)\n",
        "graph = builder.compile()\n",
        "\n",
        "# View\n",
        "display(Image(graph.get_graph().draw_mermaid_png()))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 33,
      "id": "24df63ac-da29-4874-b3df-7e390e97cc8a",
      "metadata": {
        "id": "24df63ac-da29-4874-b3df-7e390e97cc8a"
      },
      "outputs": [],
      "source": [
        "messages.append(output['messages'][-1])\n",
        "messages.append(HumanMessage(f\"Tell me where Orcas live!\", name=\"Lance\"))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 34,
      "id": "6d9d8971-c75c-43ca-a209-eb1d07b2ead0",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "6d9d8971-c75c-43ca-a209-eb1d07b2ead0",
        "outputId": "196a7e29-9082-4eff-b452-614000c4a333"
      },
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[HumanMessage(content='Tell me where Orcas live!', additional_kwargs={}, response_metadata={}, name='Lance')]"
            ]
          },
          "metadata": {},
          "execution_count": 34
        }
      ],
      "source": [
        "# Example of trimming messages\n",
        "trim_messages(\n",
        "            messages,\n",
        "            max_tokens=100,\n",
        "            strategy=\"last\",\n",
        "            token_counter=ChatGoogleGenerativeAI(model=\"gemini-1.5-flash\"),\n",
        "            allow_partial=False\n",
        "        )"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 35,
      "id": "ed70a269-a869-4fa0-a1df-29736a432c51",
      "metadata": {
        "id": "ed70a269-a869-4fa0-a1df-29736a432c51"
      },
      "outputs": [],
      "source": [
        "# Invoke, using message trimming in the chat_model_node\n",
        "messages_out_trim = graph.invoke({'messages': messages})"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "38b3db67-380e-46b5-9a6a-20100ba52008",
      "metadata": {
        "id": "38b3db67-380e-46b5-9a6a-20100ba52008"
      },
      "source": [
        "Let's look at the LangSmith trace to see the model invocation:\n",
        "\n",
        "https://smith.langchain.com/public/b153f7e9-f1a5-4d60-8074-f0d7ab5b42ef/r"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.12.1"
    },
    "colab": {
      "provenance": []
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}